package com.kancy.publicapi.common.util;

import org.springframework.util.ReflectionUtils;

import java.lang.reflect.Field;
import java.util.Optional;

/**
 * 枚举工具
 *
 * @author kancy
 * @date 2019-12-06
 */
public class EnumUtils {

    /**
     * @param clazz
     * @param code
     * @param <T>
     * @return
     */
    public static <T> Optional<T> valueOf(Class<T> clazz, String code) {
        return EnumUtils.valueOf(clazz, code, "code");
    }

    /**
     * @param clazz
     * @param value
     * @param <T>
     * @return
     */
    public static <T> Optional<T> valueOf(Class<T> clazz, String value, String key) {
        T ret = null;
        try {
            for (T result : clazz.getEnumConstants()) {
                Field codeField = result.getClass().getDeclaredField(key);
                ReflectionUtils.makeAccessible(codeField);
                if (value.equals(String.valueOf(ReflectionUtils.getField(codeField, result)))) {
                    ret = result;
                    break;
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Optional.ofNullable(ret);
    }
}
